import React, {useCallback, useEffect, useState} from 'react'
import {Button, Card, Descriptions, Form, Input, message, Space, Switch, Table as AntTable, Tag, Tooltip} from 'antd'
import {
    EditOutlined,
    InfoCircleOutlined,
    ReloadOutlined,
    SaveOutlined,
    TableOutlined,
    UnorderedListOutlined
} from '@ant-design/icons'
import type {DataSourceTreeNode, Table} from '@/types/source'
import type {ColumnsType} from 'antd/es/table'
import {sourceApi} from '@/services/api/source'

interface Props {
  selectedNode: DataSourceTreeNode | null
  onUpdated?: () => void
}

export default function TableDetailView({ selectedNode, onUpdated }: Props) {
  const [table, setTable] = useState<Table | null>(null)
  const [loading, setLoading] = useState(false)
  const [updating, setUpdating] = useState(false)
  const [editingSystemCode, setEditingSystemCode] = useState(false)
  const [form] = Form.useForm()
  // 列信息状态（动态渲染全部字段）
  const [columnsRaw, setColumnsRaw] = useState<any[]>([])
  const [columnsLoading, setColumnsLoading] = useState(false)

  const isTableNode = selectedNode?.nodeType === 'TABLE' || selectedNode?.type === 'TABLE'

  const fetchTableDetail = useCallback(async () => {
    if (!isTableNode || !selectedNode?.catalogName || !selectedNode?.databaseName || !selectedNode?.tableName) {
      return
    }

    setLoading(true)
    try {
      const table = await sourceApi.getTable(
        selectedNode.catalogName,
        selectedNode.databaseName,
        selectedNode.tableName
      )
      setTable(table)
      form.setFieldsValue({ systemCode: table.systemCode })
    } catch (error: any) {
      message.error(error?.message || '获取表信息失败')
      setTable(null)
    } finally {
      setLoading(false)
    }
  }, [selectedNode, isTableNode, form])

  const fetchColumns = useCallback(async () => {
    if (!isTableNode || !selectedNode?.catalogName || !selectedNode?.databaseName || !selectedNode?.tableName) {
      return
    }

    setColumnsLoading(true)
    try {
      const raw = await sourceApi.getColumns(
        selectedNode.catalogName,
        selectedNode.databaseName,
        selectedNode.tableName
      )
      const arr: any[] = Array.isArray(raw) ? raw as any[] : (raw as any)?.columns || (raw as any)?.list || []
      console.log('[Columns Raw]', arr)
      setColumnsRaw(arr)
    } catch (error: any) {
      message.error(error?.message || '获取列信息失败')
      setColumnsRaw([])
    } finally {
      setColumnsLoading(false)
    }
  }, [selectedNode, isTableNode])

  const handleToggleEnabled = useCallback(async (enabled: boolean) => {
    if (!selectedNode?.catalogName || !selectedNode?.databaseName || !selectedNode?.tableName) {
      return
    }

    setUpdating(true)
    try {
      await sourceApi.setTableEnabled(
        selectedNode.catalogName,
        selectedNode.databaseName,
        selectedNode.tableName,
        enabled
      )
      message.success(`表已${enabled ? '启用' : '禁用'}`)
      setTable(prev => prev ? { ...prev, enabled } : null)
      onUpdated?.()
    } catch (error: any) {
      message.error(error?.message || '更新失败')
    } finally {
      setUpdating(false)
    }
  }, [selectedNode, onUpdated])

  const handleUpdateSystemCode = useCallback(async () => {
    if (!selectedNode?.catalogName || !selectedNode?.databaseName || !selectedNode?.tableName) {
      return
    }

    try {
      const values = await form.validateFields()
      setUpdating(true)
      await sourceApi.updateTableSystemCode(
        selectedNode.catalogName,
        selectedNode.databaseName,
        selectedNode.tableName,
        values.systemCode
      )
      message.success('系统编码已更新')
      setTable(prev => prev ? { ...prev, systemCode: values.systemCode } : null)
      setEditingSystemCode(false)
      onUpdated?.()
    } catch (error: any) {
      if (error?.errorFields) return // 表单校验错误
      message.error(error?.message || '更新失败')
    } finally {
      setUpdating(false)
    }
  }, [selectedNode, form, onUpdated])

  useEffect(() => {
    if (isTableNode) {
      fetchTableDetail()
      fetchColumns()
    } else {
      setTable(null)
      setColumnsRaw([])
    }
  }, [fetchTableDetail, fetchColumns, isTableNode])

  if (!isTableNode) {
    return null
  }

  // 根据返回的所有键动态生成列定义
  const labelMap: Record<string, string> = {
    name: '列名', columnName: '列名', COLUMN_NAME: '列名', field: '列名',
    type: '数据类型', dataType: '数据类型', columnType: '数据类型', TYPE: '数据类型',
    nullable: '可空', isNullable: '可空', isNull: '可空',
    comment: '注释', columnComment: '注释', remark: '注释', COMMENT: '注释',
    defaultValue: '默认值', DEFAULT: '默认值',
    length: '长度', precision: '精度', scale: '小数位',
    primaryKey: '主键', key: '主键', KEY: '主键',
    extra: '额外', autoIncrement: '自增', ordinalPosition: '序号', charset: '字符集', collation: '排序规则',
  }

  const allKeys = Array.from(new Set(columnsRaw.flatMap((r) => Object.keys(r || {}))))
  const preferredOrder = [
    'name','columnName','COLUMN_NAME','field',
    'type','dataType','columnType','TYPE',
    'nullable','isNullable','isNull',
    'comment','columnComment','remark','COMMENT',
    'defaultValue','DEFAULT','length','precision','scale',
    'primaryKey','key','KEY','autoIncrement','ordinalPosition','extra','charset','collation'
  ]
  const sortedKeys = [...allKeys].sort((a, b) => {
    const ai = preferredOrder.indexOf(a)
    const bi = preferredOrder.indexOf(b)
    if (ai === -1 && bi === -1) return a.localeCompare(b)
    if (ai === -1) return 1
    if (bi === -1) return -1
    return ai - bi
  })

  const dynamicColumnsDefs: ColumnsType<any> = sortedKeys.map((key) => ({
    title: labelMap[key] || key,
    dataIndex: key,
    key,
    width: 160,
    align: ['nullable','isNullable','isNull','primaryKey','key','autoIncrement'].includes(key) ? 'center' : undefined,
    render: (val: any, record: any) => {
      // 特定字段美化展示
      if (key === 'name' || key === 'columnName' || key === 'COLUMN_NAME' || key === 'field') {
        const v = val ?? record?.name ?? record?.columnName ?? record?.COLUMN_NAME ?? record?.field
        return <span style={{ fontWeight: 500 }}>{String(v ?? '')}</span>
      }
      if (key === 'type' || key === 'dataType' || key === 'columnType' || key === 'TYPE') {
        return <Tag color="blue">{String(val ?? '')}</Tag>
      }
      if (key === 'nullable' || key === 'isNull') {
        const b = typeof val === 'boolean' ? val : Boolean(val)
        return <Tag color={b ? 'orange' : 'green'}>{b ? '是' : '否'}</Tag>
      }
      if (key === 'isNullable') {
        const b = String(val).toUpperCase() === 'YES'
        return <Tag color={b ? 'orange' : 'green'}>{b ? '是' : '否'}</Tag>
      }
      if (key === 'comment' || key === 'columnComment' || key === 'remark' || key === 'COMMENT') {
        const text = String(val ?? '')
        return text ? (
          <Tooltip title={text} placement="topLeft">
            <span>{text}</span>
          </Tooltip>
        ) : <span style={{ color: '#999' }}>-</span>
      }
      return String(val ?? '')
    },
  }))

  return (
    <>
      <Card
        size="small"
        title={
          <Space>
            <TableOutlined />
            表：{selectedNode?.tableName || selectedNode?.name}
          </Space>
        }
        extra={
          <Button size="small" icon={<ReloadOutlined />} onClick={fetchTableDetail} loading={loading}>
            刷新
          </Button>
        }
        loading={loading}
      >
        {table && (
          <Descriptions size="small" column={2} bordered>
            <Descriptions.Item label="表名">{table.name}</Descriptions.Item>
            <Descriptions.Item label="启用状态">
              <Switch
                checked={table.enabled}
                onChange={handleToggleEnabled}
                loading={updating}
                checkedChildren="启用"
                unCheckedChildren="禁用"
              />
            </Descriptions.Item>
            <Descriptions.Item label="系统编码" span={2}>
              {editingSystemCode ? (
                <Form form={form} layout="inline">
                  <Form.Item
                    name="systemCode"
                    rules={[{ required: true, message: '请输入系统编码' }]}
                    style={{ marginBottom: 0, flex: 1 }}
                  >
                    <Input placeholder="请输入系统编码" />
                  </Form.Item>
                  <Form.Item style={{ marginBottom: 0 }}>
                    <Space>
                      <Button
                        type="primary"
                        size="small"
                        icon={<SaveOutlined />}
                        onClick={handleUpdateSystemCode}
                        loading={updating}
                      >
                        保存
                      </Button>
                      <Button
                        size="small"
                        onClick={() => {
                          setEditingSystemCode(false)
                          form.setFieldsValue({ systemCode: table.systemCode })
                        }}
                      >
                        取消
                      </Button>
                    </Space>
                  </Form.Item>
                </Form>
              ) : (
                <Space>
                  <span>{table.systemCode || '未设置'}</span>
                  <Button type="link" size="small" icon={<EditOutlined />} onClick={() => setEditingSystemCode(true)}>
                    编辑
                  </Button>
                </Space>
              )}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Card>

      <Card
        size="small"
        title={
          <Space>
            <UnorderedListOutlined />
            列信息
            {columnsRaw.length > 0 && <Tag color="blue">{columnsRaw.length} 列</Tag>}
          </Space>
        }
        extra={
          <Space>
            <Tooltip title="列信息显示表的字段结构">
              <InfoCircleOutlined style={{ color: '#999' }} />
            </Tooltip>
            <Button size="small" icon={<ReloadOutlined />} onClick={fetchColumns} loading={columnsLoading}>
              刷新
            </Button>
          </Space>
        }
      >
        <AntTable<any>
          columns={dynamicColumnsDefs}
          dataSource={columnsRaw}
          rowKey={(r, idx) => r?.name || r?.columnName || r?.COLUMN_NAME || r?.field || String(idx)}
          loading={columnsLoading}
          size="small"
          pagination={false}
          scroll={{ y: 400, x: 'max-content' }}
          locale={{ emptyText: columnsLoading ? '加载中...' : '暂无列信息' }}
        />
      </Card>
    </>
  )
}